package hw.aspect;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.awt.*;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


@Component
@Aspect
public class StudentAspect {

    private static SqlSessionFactory factory;

    static {
        try {
            Reader r = Resources.getResourceAsReader("mybatis.cfg.xml");
            factory = new SqlSessionFactoryBuilder().build(r);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Around("execution(* hw.service..*.*(..))")
    public Object around(ProceedingJoinPoint point) {
        SqlSession session = factory.openSession();
        Object returnObj = null;
        //得到目标对象
       Object targetObj = point.getTarget();
        Field[] fieldArray = targetObj.getClass().getDeclaredFields();
        try {
        for (Field f : fieldArray) {
            if(f.getType().isInterface()){
                Object obj = session.getMapper(f.getType());
                f.setAccessible(true);
                f.set(targetObj, obj);
            }
        }
        //执行目标对象的目标方法，得到目标方法执行后的返回值
            returnObj = point.proceed();
            session.commit();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            session.rollback();
        } finally {
            session.close();
        }
        return returnObj;
    }


}
